<template>
  <m-content class="practicing-wrapper">
    <template #header-right-text>
      <span class="text">{{ state.chapter.chapterName }}</span>
      <div class="m-tooltip">
        <div class="value">
          <m-svg
            name="eye-close"
            v-if="!state.showEn"
            @click="state.showEn = true"
          ></m-svg>
          <m-svg name="eye" v-else @click="state.showEn = false"></m-svg>
        </div>
        <p class="tip">开关英语提示</p>
      </div>
    </template>
    <template #header-right-btn>
      <m-button type="primary" @click="toPage(secondaryRoutes.dictionary)"
        >选择章节</m-button
      >
    </template>

    <div class="content-wrapper">
      <p class="text">{{ state.currentWord.wordCn }}</p>
      <div class="word-box" v-if="state.currentWord.values">
        <div class="en" :class="{ error: !state.flag }">
          <m-audio :src="state.voiceUrl"></m-audio>
          <!-- 开启英文提示 -->
          <template v-if="state.showEn">
            <span
              class="fill text"
              v-for="(letter, index) in state.currentWord.values"
              :key="index"
              :class="{
                success:
                  state.inputValues[index] &&
                  letter === state.inputValues[index],
                error: !state.flag && index === state.inputValues.length
              }"
              >{{ state.currentWord.values[index] }}</span
            >
          </template>

          <!-- 关闭英文提示 -->
          <template v-else>
            <span
              class="fill"
              v-for="(letter, index) in state.currentWord.values"
              :key="index"
              :class="{
                success:
                  state.inputValues[index] &&
                  letter === state.inputValues[index],
                error: !state.flag && index === state.inputValues.length
              }"
              >{{ state.inputValues[index] }}</span
            >
          </template>
        </div>
      </div>
    </div>
  </m-content>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { secondaryRoutes } from '@/router'
import globalApi from '@/http/api'
import globalMessage from '@/components/common/message/m-message'
import { setLocalWordData, getLocalWordData } from '@/utils/util'

const api = {
  getList: globalApi.dictionaryWord.getList,
  getAll: globalApi.dictionaryWord.getAll,
  getVoice: globalApi.dictionaryWord.getVoice
}

const router = useRouter()
const route = useRoute()
const localData = getLocalWordData()
const state = reactive({
  chapter: {
    id: route.query.chapterId,
    page: route.query.page,
    dictionaryId: parseInt(route.query.dictionaryId),
    chapterName: route.query.chapterName,
    finishedCount: parseInt(
      localData[route.query.dictionaryId + '-' + route.query.chapterId]
    )
  },
  data: [],
  showEn: false,
  currentWord: {},
  inputValues: [],
  voiceUrl: '',
  flag: true
})

async function getList() {
  let res
  if (state.chapter.page) {
    // 获取分页数据
    res = await api.getList({
      dictionaryId: state.chapter.dictionaryId,
      page: state.chapter.page,
      limit: 20
    })
    state.data = res.data.rows
  } else {
    // 获取分类数据
    res = await api.getAll({
      classifyId: state.chapter.id
    })
    state.data = res.data
  }
  initValues()
}
getList()

function initValues() {
  let word = state.data[state.chapter.finishedCount]
  if (word) {
    word.values = Array.from(word.wordEn)
    state.currentWord = word
    // 获取发音
    api.getVoice({ word: word.wordEn }).then((res) => {
      state.voiceUrl = res.data.speakUrl
    })
  }
}

// 下一个
function next() {
  let lastCount = state.chapter.finishedCount + 1
  // 先存在浏览器本地缓存中
  setLocalWordData({
    [state.chapter.dictionaryId + '-' + state.chapter.id]: lastCount
  })
  // 全部完成直接返回
  if (lastCount === state.data.length) {
    globalMessage.success('本章节已全部完成，请重新选择章节')
    toPage(secondaryRoutes.dictionary)
  } else {
    // 清空然后下一条数据
    state.chapter.finishedCount = lastCount
    state.inputValues = []
    state.showEn = false
    initValues()
  }
}

function toPage(path) {
  router.push(path)
}

onMounted(function () {
  let count = 0
  document.onkeydown = (e) => {
    // 错一个全部标红闪烁  重置  重新输入
    if (e.key === state.currentWord.values[count]) {
      state.inputValues.push(e.key)
      count += 1
      // 全部正确下一个
      if (count === state.currentWord.values.length) {
        next()
        count = 0
      }
    } else {
      state.flag = false
      setTimeout(function () {
        state.flag = true
        state.inputValues = []
        count = 0
      }, 500)
    }
  }
})
</script>
